package com.vf.admin.client.controller;

import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dto.AppTuanDuiDto;
import com.vf.admin.client.service.AppAuthUserService;
import com.vf.admin.client.service.AppInvitationRecordService;
import com.vf.admin.client.service.AppSetupService;
import com.vf.admin.client.service.AppUserService;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.utils.AgeUtils;
import com.vf.admin.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

import static com.vf.admin.client.common.ClientConstants.client_toke;
import static com.vf.admin.common.Constants.guizuCacheMap;

/**
 * 邀请，我的团队
 * @author anxiang
 * @version 1.0.0
 * @ClassName AppYaoQingController.java
 * @Description TODO
 * @createTime 2021年07月28日 11:15:00
 */
@CrossOrigin
@Controller
@RequestMapping("/app/yaoqing")
public class AppYaoQingController extends ClientBaseController{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    AppInvitationRecordService appInvitationRecordService;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppSetupService appSetupService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private AppDailyTasController dailyTasController;
    @Autowired
    AppAuthUserService appAuthUserService;


    /**
     * 查询绑定关系
     * @return
     */
    @RequestMapping("/bind")
    @ResponseBody
    public Result selectBind(){
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
            AppUser user = appUserService.get(userId);
            if (user == null) {
                return this.errorJSON("用户不存在");
            }
            AppInvitationRecord appInvitationRecord = appInvitationRecordService.selectBind(userId);
            Integer status = 0;
            if (appInvitationRecord == null) {
                return this.sucessJSON(status);
            } else {
                status = 1;
                return this.sucessJSON(status);
            }
        }catch (Exception e){
            logger.error("查询绑定关系异常",e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * 通过邀请码绑定上级用户
     * @param invitationCode
     * @return
     */
    @ResponseBody
    @RequestMapping("addInvitation")
    @Transactional(rollbackFor = Exception.class)
    public Result addInvitation(String invitationCode){
        //当前用户信息
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
        AppInvitationRecord parent = appInvitationRecordService.getShangji(userId);
        if(Objects.nonNull(parent)) return this.errorJSON("邀请码不存在");
        AppUser user = appUserService.get(userId);
        //邀请用户信息
        AppUser inUser = appUserService.getUserByCode(invitationCode);
        if(Objects.isNull(inUser) || user.getId().equals(inUser.getId())){
            return this.errorJSON("邀请码错误");
        }
        //新增邀请记录
        AppInvitationRecord appInvitationRecord = new AppInvitationRecord();
        appInvitationRecord.setCreatetime(new Date());
        appInvitationRecord.setUserid(user.getId());
        appInvitationRecord.setNick(user.getNick());
        appInvitationRecord.setPic(user.getPic());
        appInvitationRecord.setPhone(user.getLoginname());
        appInvitationRecord.setSex(user.getSex());
        appInvitationRecord.setPuserid(inUser.getId());
        appInvitationRecord.setPphone(inUser.getLoginname());
        appInvitationRecord.setPpsex(inUser.getSex());
        appInvitationRecord.setPnick(inUser.getNick());
        appInvitationRecord.setPpic(inUser.getPic());
        appInvitationRecord.setCode(invitationCode);
        //添加邀请人
        AppSetup setup = appSetupService.get();
        appInvitationRecord.setSupermoney(setup.getSuperreward().doubleValue());
        appInvitationRecordService.save(appInvitationRecord);
        return this.sucessJSON("成功");
    }

    /**
    * 查看我的邀请
    * @Param: []
    * @return: com.vf.admin.common.entity.Result
    * @Author: zhouyunyi
    * @Date: 2021/07/28
    * @Time: 11:35
    */
    @RequestMapping("/yaoqing")
    @ResponseBody
    public Result yaoqing(){
        try{
            //获取最新数据
            Integer userId = (Integer)redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user =appUserService.get(userId);
            List<AppInvitationRecord> list  = appInvitationRecordService.findByYaoqingList(user.getId());
            //获取我的奖金
            AppInvitationRecord invitationRecord = appInvitationRecordService.getJiangjin(user.getId());
            //获取活动规则
            AppSetup setup = appSetupService.get();

            Map<String,Object> map = new HashMap<>(16);
            map.put("count",list.size());//已邀请个数
            map.put("yaoqingma",user.getCode());//我的邀请码
            map.put("jiangjin",invitationRecord.getJiangjin());//我的奖金
            map.put("huodongguize",setup.getHuodongguize());//活动规则
            map.put("subordinatereward",setup.getSubordinatereward());//邀请用户奖励钻石数量
            map.put("rechargeInvite",setup.getRechargeInvite());//邀请用户充值赠送比例
            map.put("giftInvite",setup.getGiftInvite());//邀请的用户礼物收益提成比例
            return this.sucessJSON(map);
        }catch (Exception e){
            logger.error("查看我的邀请信息异常",e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
    * 查看我的团队列表
    * @Param: [pageNo 页码]
    * @return: com.vf.admin.common.entity.Result
    * @Author: zhouyunyi
    * @Date: 2021/07/28
    * @Time: 16:41
    */
    @RequestMapping("/tuandui")
    @ResponseBody
    public Result tuandui(Integer pageNo){
        try{
            if (pageNo == null || pageNo <= 0) {
                return this.errorJSON("页码错误");
            }
            SplitPageBean splitPage = new SplitPageBean(pageNo, 20);
            //获取最新数据
            Integer userId = (Integer)redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user =appUserService.get(userId);
            List<AppTuanDuiDto> list = appInvitationRecordService.findByTuandui(user.getId(),splitPage);
            if (list != null && list.size() > 0){
                for(AppTuanDuiDto d : list) {
                    AppUser dUser = appUserService.get(d.getUserId());

                    int age = AgeUtils.getAgeByBirth(dUser.getBirthday());
                    d.setAge(age);
                    d.setVoiceSignature(dUser.getVoiceSignature());
                    d.setVoiceSignatureSeconds(dUser.getVoiceSignatureSeconds());
                    d.setSign(dUser.getMysign());
                    //判断用户是否是贵族
                    if (dUser.getIsguizu() == 1) {
                        //是贵族
                        //根据贵族id  获取贵族图标
                        String medal = guizuCacheMap.get(user.getNobleid());
                        d.setMedal(medal);
                    } else {
                        d.setMedal("");
                    }
                    Integer isReal = appAuthUserService.infoByUserAndName(d.getUserId(), ClientConstants.UserAuth.REAL_AUTH);
                    d.setIsReal(isReal);

                    if(dUser.getVipEndDate() != null) {
                        d.setIsVip(TimeUtils.afterNow(dUser.getVipEndDate())? 1: 0);
                    }
                }
                return this.sucessPage(list, splitPage.getNextPageNo());
            }else{
                //为空下一页标识为：-1
                return this.sucessPage(list, -1);
            }
        }catch (Exception e){
            logger.error("查看我的团队异常",e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

}
